
#include "Interop.h"
#include "./LinearMath/btScalar.h"
#include "Log.h"
#include <stdlib.h>

int InteropGetIntField(JNIEnv* env, jobject javaObj, const char* fieldName)
{
	jclass c = env->GetObjectClass(javaObj);
	jfieldID fieldID = env->GetFieldID(c, fieldName, "I");
	return env->GetIntField(javaObj, fieldID);
}

int InteropGetFloatField(JNIEnv* env, jobject javaObj, const char* fieldName)
{
	jclass c = env->GetObjectClass(javaObj);
	jfieldID fieldID = env->GetFieldID(c, fieldName, "F");
	return env->GetFloatField(javaObj, fieldID);
}

int InteropCallIntMethod(JNIEnv* env, jobject javaObj, const char* methodName)
{
	jclass c = env->GetObjectClass(javaObj);
	jmethodID methodID = env->GetMethodID(c, methodName, "()I");
	return env->CallIntMethod(javaObj, methodID);
}

int InteropCallFloatMethod(JNIEnv* env, jobject javaObj, const char* methodName)
{
//	LOGD("GetObjectClass");
	jclass c = env->GetObjectClass(javaObj);
//	LOGD("javaObj: %x", javaObj);
//	LOGD("GetMethodID, c: %x, name: %s(%x), env: %x", c, methodName, methodName, env);
	jmethodID methodID = env->GetMethodID(c, methodName, "()F");
//	LOGD("methodID: %x", methodID);
//	LOGD("CallFloatMethod");
	return env->CallFloatMethod(javaObj, methodID);
}

int InteropGetID(JNIEnv* env, jobject javaObj)
{
	return InteropCallIntMethod(env, javaObj, "getID");
}

btVector3 InteropGetVector3(JNIEnv* env, jobject vector)
{
//	LOGD("x getting");
	jfloat x = InteropCallFloatMethod(env, vector, "x");
//	LOGD("x got");
	jfloat y = InteropCallFloatMethod(env, vector, "y");
//	LOGD("y got");
	jfloat z = InteropCallFloatMethod(env, vector, "z");
//	LOGD("z got");

	return btVector3(btScalar(x), btScalar(y), btScalar(z));
}

btQuaternion InteropGetQuaternion(JNIEnv* env, jobject quaternion)
{
	jfloat a = InteropCallFloatMethod(env, quaternion, "a");
	jfloat b = InteropCallFloatMethod(env, quaternion, "b");
	jfloat c = InteropCallFloatMethod(env, quaternion, "c");
	jfloat d = InteropCallFloatMethod(env, quaternion, "d");

	return btQuaternion(btScalar(a), btScalar(b), btScalar(c), btScalar(d));
}
